package com.leyou.auth.interceptors;

import com.auth.constants.JwtConstants;
import com.auth.dto.Payload;
import com.auth.dto.UserDetails;
import com.auth.utils.JwtUtils;
import com.leyou.auth.utils.UserContext;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.CookieUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//判断用户是否登录
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    private JwtUtils jwtUtils;

    public LoginInterceptor(JwtUtils jwtUtils) {
        this.jwtUtils = jwtUtils;
    }

    //要写在前置处理器，前置处理器和后置处理器之间就是代码了
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.获取用户cookie中的jwt
        String jwt = CookieUtils.getCookieValue(request, JwtConstants.COOKIE_NAME);

        System.out.println("preHandle->0`0>jwt");
        System.out.println("preHandle->>jwt = " + jwt);
        if(StringUtils.isBlank(jwt)){
            // jwt为空，未登录
            throw new LyException(401, "未登录！");
        }
        // 2.验证jwt，获取用户信息
        //从cookie中获取用户携带的jwt进行验证
        Payload payload = jwtUtils.parseJwt(jwt);
        UserDetails user = payload.getUserDetail();
        // 3.判断结果，如果正确则放行
        if (user == null) {
            throw new LyException(401, "未登录！");
        }
        // 保存用户
        UserContext.setUser(user);
        //保存用户jwt，在远程调用时候添加到里面能够获取到不至于没有权限访问
        UserContext.setJwt(jwt);
        // 无论如何都要放行
        log.info("用户{}正在访问。", user.getUsername());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 业务结束后，移除用户
        UserContext.removeUser();
    }
}
